package com.hwadee.property.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hwadee.property.dto.RepairsPersonal;
import com.hwadee.property.mapper.RepairMapper;
import com.hwadee.property.pojo.House;
import com.hwadee.property.pojo.Repair;
import com.hwadee.property.service.IBuildingService;
import com.hwadee.property.service.IHouseService;
import com.hwadee.property.service.IRepairService;
import com.hwadee.property.dto.PageResult;
import com.hwadee.property.service.IUserService;
import com.hwadee.property.util.DateUtil;
import com.hwadee.property.util.DtoUtil;
import com.hwadee.property.util.ErrorCodes;
import com.hwadee.property.util.BusinessException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import java.util.*;

@Service
public class RepairServiceImpl extends ServiceImpl<RepairMapper, Repair> implements IRepairService {

    @Autowired
    private RepairMapper repairMapper;

    @Autowired
    private IHouseService houseService;

    @Autowired
    private IBuildingService buildingService;

    @Autowired
    private IUserService userService;

    @Autowired
    private DtoUtil dtoUtil;

    @Override
    public PageResult<Repair> getPage(int current, int size, Long communityId, String processingStatus) {
        current = Math.max(current, 1);
        size = Math.max(size, 1);
        int offset = (current - 1) * size;

        int total = repairMapper.countRepairs(processingStatus, communityId);
        List<Repair> records = total > 0
                ? repairMapper.getRepairsPage(processingStatus, communityId, size, offset)
                : Collections.emptyList();

        return new PageResult<>(total, current, size, records);
    }

    @Override
    public List<Repair> listByHouseId(Long houseId) {
        // 检查房屋 ID 是否合法
        if (houseId == null || houseId <= 0) {
            throw new BusinessException(ErrorCodes.INVALID_PARAMETER, "房屋 ID 无效");
        }
        return this.list(new QueryWrapper<Repair>().eq("house_id", houseId));
    }

    @Override
    public boolean updateStatus(Long repairId, String status) {
        // 检查状态是否合法
        if (!isValidStatus(status)) {
            throw new BusinessException(ErrorCodes.INVALID_PARAMETER, "status 的值不合法，必须为 '待处理'、'处理中'、'已完成' 或 '已取消'");
        }

        // 检查报修记录是否存在
        Repair repair = this.getById(repairId);
        if (repair == null) {
            throw new BusinessException(ErrorCodes.NOT_FOUND, "报修记录不存在");
        }

        // 更新报修状态
        repair.setProcessingStatus(status);
        return this.updateById(repair);
    }

    @Override
    public boolean assignHandler(Long repairId, Long handlerId) {
        // 检查报修记录是否存在
        Repair repair = this.getById(repairId);
        if (repair == null) {
            throw new BusinessException(ErrorCodes.NOT_FOUND, "报修记录不存在");
        }

        // 分配处理人员
        repair.setHandlerId(handlerId);
        repair.setStartDate(DateUtil.dateToString(new Date())); // 设置接受处理时间
        return this.updateById(repair);
    }

    @Override
    public List<Repair> listByStatus(String status) {
        // 检查状态是否合法
        if (!isValidStatus(status)) {
            throw new BusinessException(ErrorCodes.INVALID_PARAMETER, "status 的值不合法，必须为 '待处理'、'处理中'、'已完成' 或 '已取消'");
        }

        // 根据状态查询报修记录
        return this.list(new QueryWrapper<Repair>().eq("processing_status", status));
    }

    @Override
    public boolean completeRepair(Long repairId, String feedBack) {
        // 检查报修记录是否存在
        Repair repair = this.getById(repairId);
        if (repair == null) {
            throw new BusinessException(ErrorCodes.NOT_FOUND, "报修记录不存在");
        }

        // 完成报修并记录反馈
        repair.setProcessingStatus("已完成");
        repair.setCompletionDate(DateUtil.dateToString(new Date())); // 设置完成时间
        repair.setFeedBack(feedBack); // 设置反馈
        return this.updateById(repair);
    }

    @Override
    public List<Repair> listByOwnerId(Long userId) {
        List<Repair> repairs = new ArrayList<>();
        List<House> houses = houseService.listByOwnerId(userId);
        for (House i : houses) {
            repairs.addAll(listByHouseId(i.getId())); // 使用 addAll 方法将返回的 List<Repair> 添加到 repairs 中
        }
        return repairs; // 直接返回 repairs 列表
    }

    @Override
    public List<RepairsPersonal> listByOwnerIdPersonal(Long userId) {
        List<Repair> repairs = new ArrayList<>();
        List<RepairsPersonal> repairsPersonals = new ArrayList<>();
        List<House> houses = houseService.listByOwnerId(userId);
        for (House i : houses) {
            repairs.addAll(listByHouseId(i.getId())); // 使用 addAll 方法将返回的 List<Repair> 添加到 repairs 中
        }

        for (Repair i : repairs){
            RepairsPersonal repairsPersonal = new RepairsPersonal();
            repairsPersonal.setId(i.getId());
            repairsPersonal.setHouseId(i.getHouseId());
            repairsPersonal.setHouseName(dtoUtil.getHouseName(houseService.getById(i.getHouseId())));
            repairsPersonal.setContent(i.getRepairContent());
            repairsPersonal.setStatus(i.getProcessingStatus());
            repairsPersonal.setCreateTime(i.getCreateTime());
            repairsPersonal.setRepairDate(i.getRepairDate());
            if (i.getHandlerId() != null)repairsPersonal.setHandlerName(userService.getById(i.getHandlerId()).getName());
            repairsPersonal.setStartDate(i.getStartDate());
            repairsPersonal.setCompletionDate(i.getCompletionDate());
            repairsPersonal.setFeedback(i.getFeedBack());
            repairsPersonals.add(repairsPersonal);
        }
        return repairsPersonals; // 直接返回 repairs 列表
    }


    /**
     * 检查状态值是否合法
     *
     * @param status 状态值
     * @return 如果状态值合法返回 true，否则返回 false
     */
    private boolean isValidStatus(String status) {
        return "待处理".equals(status) || "处理中".equals(status) || "已完成".equals(status) || "已取消".equals(status);
    }
}
